// Header file generation tool
// Translated from Rust version to Go version with optimizations
package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"
)

const (
	// Header file name
	headerFileName = "build_info.h"
	// Version numbers
	versionMajor = 0
	versionMinor = 0
	defaultPatch = 1 // Default patch version number 1
)

// 创建新的版本头文件
func createNewVersionHeaderFile() error {
	// 获取当前Unix时间戳（从1970年1月1日UTC开始的秒数）
	unixTimestamp := time.Now().Unix()

	// 获取格式化的时间字符串
	formattedTime := time.Now().Format("2006-01-02 15:04:05")

	// 创建头文件内容
	content := fmt.Sprintf(`#ifndef BUILD_INFO_H
#define BUILD_INFO_H
#define BUILD_TIME_STAMP %d
#define BUILD_VERSION_MAJOR %d
#define BUILD_VERSION_MINOR %d
#define BUILD_VERSION_PATCH %d
#endif // BUILD_INFO_H

`, unixTimestamp, versionMajor, versionMinor, defaultPatch)

	// 写入文件
	err := os.WriteFile(headerFileName, []byte(content), 0644)
	if err != nil {
		return fmt.Errorf("failed to create header file: %w", err)
	}

	// 打印详细信息
	log.Print("header file created successfully")
	log.Printf("timestamp \"%d\"", unixTimestamp)
	log.Printf("corresponding time: \"%s\"", formattedTime)
	return nil
}

// 更新版本头文件中的时间戳和版本号
func updateVersionHeaderFile() error {
	// 读取现有文件
	file, err := os.Open(headerFileName)
	if err != nil {
		return fmt.Errorf("failed to open header file: %w", err)
	}
	defer file.Close()

	// 读取所有行
	var lines []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		return fmt.Errorf("failed to read header file: %w", err)
	}

	// 获取当前Unix时间戳
	unixTimestamp := time.Now().Unix()

	// 获取格式化的时间字符串
	formattedTime := time.Now().Format("2006-01-02 15:04:05")

	// 正则表达式匹配时间戳行和补丁版本行
	timestampRegex := regexp.MustCompile(`#define BUILD_TIME_STAMP \d+`)
	patchRegex := regexp.MustCompile(`#define BUILD_VERSION_PATCH (\d+)`)

	// 更新时间戳和补丁版本号
	var timestampFound, patchFound bool
	currentPatch := defaultPatch

	for i, line := range lines {
		// 更新时间戳
		if timestampRegex.MatchString(line) {
			lines[i] = fmt.Sprintf(`#define BUILD_TIME_STAMP %d`, unixTimestamp)
			timestampFound = true
		}

		// 更新补丁版本号
		if patchMatch := patchRegex.FindStringSubmatch(line); len(patchMatch) > 1 {
			currentPatch, _ = strconv.Atoi(patchMatch[1])
			currentPatch++ // 增加补丁版本号
			lines[i] = fmt.Sprintf(`#define BUILD_VERSION_PATCH %d`, currentPatch)
			patchFound = true
		}
	}

	if !timestampFound {
		return fmt.Errorf("timestamp definition line not found")
	}

	if !patchFound {
		return fmt.Errorf("patch version definition line not found")
	}

	// 写回文件
	output := strings.Join(lines, "\n") + "\n"
	err = os.WriteFile(headerFileName, []byte(output), 0644)
	if err != nil {
		return fmt.Errorf("failed to update header file: %w", err)
	}

	// 打印详细信息
	// log.Printf("Head file update")
	log.Printf("timestamp \"%d\"", unixTimestamp)
	log.Printf("corresponding time: \"%s\"", formattedTime)
	log.Printf("new version: %d", currentPatch)

	return nil
}

func main() {
	// 设置日志格式
	log.SetPrefix("[Stamp Update] ")
	log.SetFlags(0)
	// 获取当前工作目录
	workDir, err := os.Getwd()
	if err != nil {
		log.Fatalf("failed to get working directory: %v", err)
	}

	// 构建头文件完整路径
	headerFilePath := filepath.Join(workDir, headerFileName)

	// 检查头文件是否存在
	_, err = os.Stat(headerFilePath)
	if os.IsNotExist(err) {
		// 文件不存在，创建新文件
		if err := createNewVersionHeaderFile(); err != nil {
			log.Fatalf("failed to create header file: %v", err)
		}
	} else if err != nil {
		// 其他错误
		log.Fatalf("failed to check header file status: %v", err)
	} else {
		// 文件存在，更新时间戳
		if err := updateVersionHeaderFile(); err != nil {
			log.Fatalf("failed to update header file: %v", err)
		}
	}
}
